package com.example.commonutils.controller;


import com.example.commonutils.common.ExcelUtil;
import com.example.commonutils.domain.UserData;
import com.example.commonutils.service.DataService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;


/**
 * @author tianzhuang
 */
@Api(tags = "Excel的导入导出")
@RestController
public class ExportExcelController {

    @Autowired
    private DataService dataService;

    /**
     *   在浏览器地址栏输入此接口地址，即可导出Excel，用swagger导出是乱码，暂未解决
     * @param response
     * @throws IOException
     */
    @ApiOperation(value = "导出",produces="application/octet-stream")
    @GetMapping("/exportExcel")
    public void exportExcel(HttpServletResponse response) throws IOException {
        List<UserData> userData = dataService.selectUserData();
        ExcelUtil<UserData> util = new ExcelUtil<UserData>(UserData.class);
        util.exportExcel(response,userData , "角色数据");
    }

    /**
     *
     * @param file
     * @return
     * @throws Exception
     */
    @ApiOperation("导入")
    @PostMapping("/importExcel")
    public int importExcel(MultipartFile file) throws Exception {
        ExcelUtil<UserData> util = new ExcelUtil<>(UserData.class);
        List<UserData> userDataList = util.importExcel(file.getInputStream());
        int insertFlag = dataService.importUserData(userDataList);
        if (insertFlag == 0){
            throw new RuntimeException("导入失败");
        }
        return insertFlag;
    }
}
